<template>
  <el-dropdown
      class="lang-switch-box"
      @command="handleLangChange"
      placement="bottom"
  >
    <span class="lang-switch-trigger">
<!--      <el-icon><globe /></el-icon>-->
      <span class="lang-text">{{ currentLangText }}</span>
      <img :src="getIamge(locale)" alt="" width="30" height="20">
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item command="zh-CN">中文</el-dropdown-item>
        <el-dropdown-item command="en-US">English</el-dropdown-item>
        <el-dropdown-item command="vi-VN">Tiếng Việt</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
import {computed, onMounted} from 'vue'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
// import { Globe } from '@element-plus/icons-vue'
import { currentLocale } from '@/i18n'
import {
  Query,Save
} from "@/api";
import zhCN from '@/assets/zh-CN.jpg'
import enUS from '@/assets/en-US.jpg'
import viVN from '@/assets/vi-VN.jpg'

const { locale } = useI18n()

// 语言文本映射
const langMap = {
  'zh-CN': '中文',
  'en-US': 'English',
  'vi-VN': 'Tiếng Việt'
}
const getIamge = (locale) => {
  switch (locale) {
    case 'zh-CN':
      return zhCN
    case 'en-US':
      return enUS
    case 'vi-VN':
      return viVN
    default:
      return zhCN
  }
}
const getCurrentLang = async () => {
  const res = await Query({
    operType:'GetLanguage'
  })
  if (res.code === 200) {
    console.log('当前语言', res.data)
    locale.value = res.data[0].Value
    currentLocale.value = res.data[0].Value // 同步到本地存储
  }
}

const saveCurrentLang = async (lang) => {
  const res = await Save({
    OperType:'SaveLanguage',
    JsonData:{Language: lang}
  })
  if (res.code === 200) {
    ElMessage.success('切换成功')
  }
}

// 当前语言文本
const currentLangText = computed(() => langMap[locale.value])

// 切换语言
const handleLangChange = (lang) => {
  locale.value = lang
  currentLocale.value = lang // 同步到本地存储
  // saveCurrentLang(lang)
}
onMounted(() => {
  // 初始化语言
  getCurrentLang()
})
</script>

<style scoped>
.lang-switch-box{
  border:1px solid #409eff;
  border-radius: 5px;
  margin-left: 10px;
}
.lang-text {
  font-size: 22px;
  margin-right: 10px;
}
.lang-switch-trigger {
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  padding: 0 10px;
  color: #409eff;
}
</style>
